//
//  YAYICertificationViewController.m
//  YAYIDoctor
//
//  Created by Veer on 16/5/4.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYICertificationViewController.h"
#import "YAYIMyQRCodeViewController.h"

#import "YAYIEditPhotoView.h"
#import "AFNetworking.h"
#import <AVFoundation/AVFoundation.h>

@interface YAYICertificationViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate,YAYIEditPhotoViewDelegate, UIAlertViewDelegate>

@property (nonatomic, weak) UIScrollView *containScrollView;

@property (nonatomic, weak) UILabel *titleLbl;
@property (nonatomic, weak) YAYIEditPhotoView *editPhotoView;
@property (nonatomic, weak) UIButton *selectPhotoBtn;
@property (nonatomic, weak) UIImageView *verifyImageView;

@property (nonatomic, weak) UIView *bottomView;
@property (nonatomic, strong) NSData *selectImageData;

@property (nonatomic, strong) AFURLSessionManager *manager;

@end

@implementation YAYICertificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"实名认证";
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self setupNav];
    
    [self setupSubView];
    [self setupBottomView];
    [self getVerify];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    YAYIMyQRCodeViewController *vc = self.navigationController.childViewControllers.lastObject;
    if ([vc isKindOfClass:[YAYIMyQRCodeViewController class]]) {
        [vc refreshPage];
    }
}


- (void)viewDidLayoutSubviews
{
    
    self.containScrollView.contentSize = CGSizeMake(SCREEN_width, CGRectGetMaxY(self.bottomView.frame) + 20);
    YAYILog(@"viewDidLayoutSubviews:%f", CGRectGetMaxY(self.bottomView.frame));
}


- (void)dealloc
{
    // 停止所有操作
    [self.manager.operationQueue cancelAllOperations];
}


- (void)setupNav
{
    if (!self.isShowJump) {
        return;
    }

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [button setImage:[UIImage imageNamed:@"back_button"] forState:UIControlStateNormal];
    [button setTitle:@"跳过" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    button.frame = (CGRect){{0, 0}, CGSizeMake(70, 30)};
    
    // 让按钮内部的所有内容左对齐
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [button addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 修改导航栏左边的item
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}


- (void)setupSubView
{
    
    UIScrollView *containScrollView = [[UIScrollView alloc] init];
    containScrollView.frame = self.view.bounds;
    containScrollView.alwaysBounceVertical = YES;
    [self.view addSubview:containScrollView];
    self.containScrollView = containScrollView;
    
    //
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = @"请上传医师执业证书或手持工牌照";
    titleLbl.font = [UIFont systemFontOfSize:16];
    [containScrollView addSubview:titleLbl];
    self.titleLbl = titleLbl;
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20 + 64);
        make.centerX.equalTo(self.view);
    }];
    
    // 选择图片按钮
    UIButton *selectPhotoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    selectPhotoBtn.backgroundColor = [UIColor yellowColor];
    [selectPhotoBtn setBackgroundImage:[UIImage imageNamed:@"uploadIcon"] forState:UIControlStateNormal];
    [selectPhotoBtn addTarget:self action:@selector(selectPhotoAction:) forControlEvents:UIControlEventTouchUpInside];
    [containScrollView addSubview:selectPhotoBtn];
    self.selectPhotoBtn = selectPhotoBtn;
    [selectPhotoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(90 * YAYIScreenScale));
        make.height.equalTo(@(90 * YAYIScreenScale));
        make.centerX.equalTo(self.view);
        make.top.equalTo(titleLbl.mas_bottom).offset(20);
    }];
    
    
    UIImageView *verifyImageView = [[UIImageView alloc] init];
    verifyImageView.hidden = YES;
    verifyImageView.userInteractionEnabled = YES;
    [containScrollView addSubview:verifyImageView];
    self.verifyImageView = verifyImageView;
    [verifyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(titleLbl.mas_bottom).offset(20);
        make.width.equalTo(@(200 * YAYIScreenScale));
        make.height.equalTo(@(90 * YAYIScreenScale));
    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageGestureHandel:)];
    [verifyImageView addGestureRecognizer:tap];
    
    
    // 底部view
    UIView *bottomView = [[UIView alloc] init];
//    bottomView.backgroundColor = [UIColor yellowColor];
    [containScrollView addSubview:bottomView];
    self.bottomView = bottomView;
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.equalTo(self.view);
        make.left.right.equalTo(self.view);
        make.top.equalTo(verifyImageView.mas_bottom).offset(20);
    }];
    
}


- (void)setupBottomView
{
    UILabel *descLbl1 = [[UILabel alloc] init];
    descLbl1.text = @"• 上传的照片仅用于认证，患者和第三方不会看到您的信息；";
    descLbl1.numberOfLines = 0;
    descLbl1.font = [UIFont systemFontOfSize:13];
    descLbl1.textColor = YAYIColor(99, 98, 98);
    [self.bottomView addSubview:descLbl1];
    [descLbl1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@30);
        make.right.equalTo(@-30);
        make.top.equalTo(@0);
    }];
    
    UILabel *descLbl2 = [[UILabel alloc] init];
    descLbl2.text = @"• 拍照时，请确保姓名、照片、编号、执业范围等信息清晰可辨认，信息越齐全，越有助于认证；";
    descLbl2.numberOfLines = 0;
    descLbl2.font = [UIFont systemFontOfSize:13];
    descLbl2.textColor = YAYIColor(99, 98, 98);
    [self.bottomView addSubview:descLbl2];
    [descLbl2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@30);
        make.right.equalTo(@-30);
        make.top.equalTo(descLbl1.mas_bottom).offset(5);
    }];
    
    UILabel *descLbl3 = [[UILabel alloc] init];
    descLbl3.text = @"• 未经审核的用户无法使用完整功能。";
    descLbl3.numberOfLines = 0;
    descLbl3.textColor = YAYIColor(99, 98, 98);
    descLbl3.font = [UIFont systemFontOfSize:13];
    [self.bottomView addSubview:descLbl3];
    [descLbl3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@30);
        make.right.equalTo(@-30);
        make.top.equalTo(descLbl2.mas_bottom).offset(5);
    }];
    
    UIImageView *sampleView = [[UIImageView alloc] init];
    sampleView.image = [UIImage imageNamed:@"border"];
    [self.bottomView addSubview:sampleView];
    [sampleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@32);
        make.right.equalTo(@-32);
        make.height.equalTo(@(174 * YAYIScreenScale));
        make.top.equalTo(descLbl3.mas_bottom).offset(20);
    }];
    
    UILabel *sampleLbl1 = [[UILabel alloc] init];
    sampleLbl1.text = @"示例";
    sampleLbl1.numberOfLines = 0;
//    sampleLbl1.textColor = YAYIColor(99, 98, 98);
    sampleLbl1.font = [UIFont systemFontOfSize:13];
    [sampleView addSubview:sampleLbl1];
    [sampleLbl1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@10);
        make.top.equalTo(@10);
    }];
    
    UILabel *sampleLbl2 = [[UILabel alloc] init];
    sampleLbl2.text = @"或";
    sampleLbl2.numberOfLines = 0;
//    sampleLbl2.textColor = YAYIColor(99, 98, 98);
    sampleLbl2.font = [UIFont systemFontOfSize:13];
    [sampleView addSubview:sampleLbl2];
    [sampleLbl2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(sampleView);
        make.centerY.equalTo(sampleView);
    }];
    
    // 示例图片
    UIImageView *sampleImgView1 = [[UIImageView alloc] init];
    sampleImgView1.image = [UIImage imageNamed:@"sample1"];
    [sampleView addSubview:sampleImgView1];
    [sampleImgView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(sampleView).multipliedBy(0.5);
        make.centerY.equalTo(sampleView).multipliedBy(1);
        make.width.equalTo(@70);
        make.height.equalTo(@70);
    }];
    
    UILabel *sampleLbl3 = [[UILabel alloc] init];
    sampleLbl3.text = @"医师执业证书";
    sampleLbl3.textColor = YAYIColor(99, 98, 98);
    sampleLbl3.font = [UIFont systemFontOfSize:12];
    [sampleView addSubview:sampleLbl3];
    [sampleLbl3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(sampleImgView1);
        make.top.equalTo(sampleImgView1.mas_bottom).offset(15 * YAYIScreenScale);
    }];
    
    // 示例图片2
    UIImageView *sampleImgView2 = [[UIImageView alloc] init];
    sampleImgView2.image = [UIImage imageNamed:@"sample2"];
    [sampleView addSubview:sampleImgView2];
    [sampleImgView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(sampleView).multipliedBy(1.5);
        make.centerY.equalTo(sampleView).multipliedBy(1);
        make.width.equalTo(@70);
        make.height.equalTo(@70);
    }];
    
    UILabel *sampleLbl4 = [[UILabel alloc] init];
    sampleLbl4.text = @"手持工牌照";
    sampleLbl4.textColor = YAYIColor(99, 98, 98);
    sampleLbl4.font = [UIFont systemFontOfSize:12];
    [sampleView addSubview:sampleLbl4];
    [sampleLbl4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(sampleImgView2);
        make.top.equalTo(sampleImgView2.mas_bottom).offset(15 * YAYIScreenScale);
    }];
    
    // 提交按钮
    UIButton *subBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [subBtn setBackgroundImage:[UIImage imageNamed:@"button_normal"] forState:UIControlStateNormal];
    [subBtn setTitle:@"提交" forState:UIControlStateNormal];
    [subBtn addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:subBtn];
    [subBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(44));
        make.left.equalTo(@(20));
        make.right.equalTo(@(-20));
        make.top.equalTo(sampleView.mas_bottom).offset(30 * YAYIScreenScale);
     }];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(subBtn);
    }];
}

#pragma mark - 获取数据
- (void)getVerify
{
    
    [YAYINetWorking getWithURL:me_queryLastVerify param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            
            YAYILog(@"返回:%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                return;
            }else{
                
                self.verifyImageView.hidden = NO;
                __block UIImageView *weakimage = self.verifyImageView;
                __block typeof(self) weakself = self;
                if (dict[@"data"] && ![dict[@"data"] isKindOfClass:[NSNull class]]) {
                    
//                    self.state = [dict[@"data"][@"state"] integerValue];
                    
                    NSString *urlStr = dict[@"data"][@"img"];
                    urlStr = [NSString stringWithFormat:@"%@%@", API, urlStr];
                    [self.verifyImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                        
                        CGFloat imageH = 200 / image.size.width * image.size.height;
                        imageH = imageH < 200 ? 200 : imageH;
                        
                        [weakimage mas_updateConstraints:^(MASConstraintMaker *make) {
                            make.width.mas_offset(200 * YAYIScreenScale);
                            make.height.mas_offset(imageH * YAYIScreenScale);
                        }];
                        [weakself.bottomView layoutIfNeeded];
                    }];
                }
            }
        }
    }];
}


#pragma mark - 点击事件方法
- (void)goBack
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)cancelAction:(UIButton *)sender
{
    YAYILog(@"点击了取消");
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"" message:@"跳过实名认证，会影响您的部分功能体验！" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    [alertVc addAction:action1];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
//        [self.navigationController popToRootViewControllerAnimated:YES];
    }];
    [alertVc addAction:action2];
    [self presentViewController:alertVc animated:YES completion:nil];
}


- (void)submitAction:(UIButton *)sender
{
    if (self.selectImageData == nil) {
        [SVProgressHUD showImage:nil status:@"\n\n请上传图片\n\n"];
        
        return;
    }
    
    NSData *imgData = self.selectImageData;
    
    YAYILog(@"imgData.length:%ld", imgData.length);

    // 1.创建请求管理对象
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    self.manager = mgr;
//    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    mgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"application/json", nil];
    mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    mgr.requestSerializer=[AFJSONRequestSerializer serializer];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", API, uploadCerImg_url];
    // 2.发送请求
    [mgr POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:imgData name:@"certification" fileName:@"certification.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        [SVProgressHUD showProgress:uploadProgress.fractionCompleted status:@"图片上传中..."];
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        YAYILog(@"返回：%@", responseObject);
        
        if (responseObject == nil || [responseObject isKindOfClass:[NSNull class]] || ![responseObject[@"status"] isEqualToString:@"success"]) {
            
            
            [SVProgressHUD dismiss];
            [SVProgressHUD showErrorWithStatus:@"上传失败"];
            
        }else{
            
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            
            __block typeof(self) weakself = self;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                if (weakself.isShowJump) {
                    
                    [weakself.navigationController dismissViewControllerAnimated:YES completion:nil];
                }else{
                    
                    if (weakself.backOperation) {
                        weakself.backOperation();
                    }
                    [weakself.navigationController popViewControllerAnimated:YES];
                }
            });
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:@"上传失败"];
    }];
}


- (void)selectPhotoAction:(UIButton *)sender
{
    YAYILog(@"点击了选择图片");
    
    [self chooseImage];
}


- (void)imageGestureHandel:(UITapGestureRecognizer *)tapRecongnizer
{
    
    if (self.state == 2) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"您已认证成功，是否重新上传认证？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
        return;
    }else if (self.state == 2) {
    
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"认证审核中，是否重新上传认证？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
        return;
    }
    
    [self chooseImage];
}


- (void)chooseImage
{
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"想选择图片来源" message:@"选择一个图片source" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *imageAlume = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController *imagePicker = [UIImagePickerController new];
        //        imagePicker.allowsEditing = YES;
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    }];
    [alertVc addAction:imageAlume];
    
    UIAlertAction *takePhoes = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //打开相册
        UIImagePickerController *pickView = [[UIImagePickerController alloc]init];
        pickView.delegate = self;
        pickView.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:pickView animated:YES completion:nil];
    }];
    [alertVc addAction:takePhoes];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //打开相册
        //            [self openAlume];
    }];
    [alertVc addAction:cancel];
    
    [self presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark 工具方法
/**
 *  压缩图片
 *
 *  @param image       被压缩图片
 *  @param maxFileSize 压缩后尺寸
 *
 */
- (NSData *)compressImage:(UIImage *)image toMaxFileSize:(NSInteger)maxFileSize
{
    
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    
    YAYILog(@"imageData length:%ld", imageData.length);
    
    while ([imageData length] > maxFileSize && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
        YAYILog(@"imageData length:%ld", imageData.length);
    }
    
    UIImage *compressedImage = [UIImage imageWithData:imageData];
    
    YAYILog(@"compressedImage length:%ld", UIImageJPEGRepresentation(compressedImage, compression).length);
    
    return imageData;
}

#pragma mark - 各种代理方法
#pragma mark UIAlertView代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self chooseImage];
    }
}


-(void)editPhotoViewToOpenAblum:(YAYIEditPhotoView *)editView{

    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"想选择图片来源" message:@"选择一个图片source" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *imageAlume = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVc addAction:imageAlume];

    UIAlertAction *takePhoes = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //打开相册
        UIImagePickerController *pickView = [[UIImagePickerController alloc]init];
        pickView.delegate = self;
        pickView.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:pickView animated:YES completion:nil];
    }];
    [alertVc addAction:takePhoes];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //打开相册
        //            [self openAlume];
    }];
    [alertVc addAction:cancel];
    
    [self presentViewController:alertVc animated:YES completion:nil];

}




- (void)editPhotoViewHeightChanged:(CGFloat)curHeight
{
    [self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLbl.mas_bottom).offset(curHeight + 20);
    }];
}

//点击图片成功
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary<NSString *,id> *)editingInfo{
    
    NSData *selectImageData = [self compressImage:image toMaxFileSize:1 * 1024 * 1024];
    self.selectImageData = selectImageData;
    
    self.verifyImageView.image = [UIImage imageWithData:selectImageData];
    
    CGFloat imageH = 200 / image.size.width * image.size.height;
    imageH = imageH < 200 ? 200 : imageH;
    [self.verifyImageView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset(200 * YAYIScreenScale);
        make.height.mas_offset(imageH * YAYIScreenScale);
    }];
    
    // 改变contentSize
    [self.bottomView layoutIfNeeded];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//点击pickerview的取消，不加图片了
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


@end
